import { DesktopOutlined, FileOutlined, PieChartOutlined, TeamOutlined, UserOutlined } from '@ant-design/icons';
import { Menu, MenuProps, theme } from 'antd';
import { SubMenuType } from 'antd/es/menu/hooks/useItems';
import { useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';

type MenuItem = Required<MenuProps>['items'][number];

function getItem(label: React.ReactNode, key: React.Key, icon?: React.ReactNode, children?: MenuItem[]): SubMenuType {
  return {
    key,
    icon,
    children,
    label,
  } as SubMenuType;
}

const items: SubMenuType[] = [
  getItem('page1', '/page1', <PieChartOutlined />),
  getItem('page2', '/page2', <DesktopOutlined />),
  getItem('others', '', <UserOutlined />, [
    getItem('page3', '/page3'),
    getItem('page4', '/page4'),
    getItem('Alex', '5'),
  ]),
  getItem('Team', 'page4', <TeamOutlined />, [getItem('Team 1', '6'), getItem('Team 2', '8')]),
  getItem('Files', '9', <FileOutlined />),
];

const Comp: React.FC = () => {
  // 路由跳转
  const navigateTo = useNavigate();
  // 当前路由
  const currentRoute = useLocation();
  const {
    token: { colorBgContainer },
  } = theme.useToken();
  //   菜单点击事件
  const menuClick = (e: { key: string }) => {
    // 点击跳转路由  编程式导航跳转 利用hook useNavigate
    navigateTo(e.key);
  };
  // 拿到currentRout.pathname跟items的每一项children的key值对比，如果找到了相等的，就拿到它上一级的key
  let firstOpenKey: string = '';
  // 对比
  function findKey(obj: { key: string }) {
    return obj.key === currentRoute.pathname;
  }
  items.forEach((item) => {
    // 判断在哪里找到
    if (
      item['children'] &&
      item['children'].length > 0 &&
      item['children'].find((obj: any) => {
        obj.key === currentRoute.pathname;
      })
    ) {
      firstOpenKey = item.key;
    }
  });
  /* for (let i = 0; i < items.length; i++) {
    // 判断在哪里找到
    if (items[i]['children'] && items[i]['children'].length > 0 && items[i]['children'].find(findKey)) {
      firstOpenKey = items[i].key as string;
      break;
    }
  } */
  // 设置展开项的初始值
  const [openKeys, setOpenKeys] = useState(['']);
  //   菜单打开关闭
  const handleOpenChange = (keys: string[]) => {
    // keys是一个数组，记录了当前哪一项是展开的
    // 把这个数组改成最后一项，只需要有一个是展开的
    console.log(keys);
    setOpenKeys([keys[keys.length - 1]]);
  };
  return (
    <Menu
      theme="dark"
      defaultSelectedKeys={[currentRoute.pathname]}
      mode="inline"
      items={items}
      onClick={menuClick}
      //   某项菜单展开回收
      onOpenChange={handleOpenChange}
      //   当前菜单展开项的key数组
      openKeys={openKeys}
    />
  );
};

export default Comp;
